'''
数据库相关的操作
'''
import pymysql


def connect(db_info: dict):
    """
    连接数据库
    :param db_info: 字典格式的，数据库相关的信息
            {"host":"192.168.0.103","port":3306,"user":"root","pwd":"123456","dbname":"apple"}
    :return: 连接对象
    """
    try:
        conn = pymysql.connect(user=db_info['user'],
                               password=db_info['pwd'],
                               host=db_info['host'],
                               database=db_info['dbname'],
                               port=db_info['port'],
                               charset='utf8')
        print("连接数据库成功")
        return conn
    except Exception as e:
        print(f"连接数据库异常，异常信息为：{e}")


def disconnect(conn):
    """
    断开连接
    :param conn:连接对象
    :return:
    """
    try:
        conn.close()
    except Exception as e:
        print(f"断开数据库连接异常，异常信息为：{e}")


def execute(coon, sql):
    try:
        c = coon.cursor()  # 获取游标，类似creatstatement
        c.execute(sql)  # 使用游标执行sql语句
        coon.commit()  # 提交
        print(f"执行{sql}成功")
    except Exception as e:
        print(f"执行{sql}异常，异常信息为：{e}")


def delete_user(db_info, phone):
    """
    根据手机号码删除用户
    :param phone:
    :return:
    """
    coon = connect(db_info)
    execute(coon, f"delete from member where mobilephone={phone}")
    disconnect(coon)

# 可删除
if __name__ == '__main__':
    db_info = {"host": "192.168.0.103", "port": 3306, "user": "root", "pwd": "123456", "dbname": "apple"}
    # coon = connect(db_info)
    # execute(coon,"delete from member where mobilephone=18710944088")
    # disconnect(coon)
    delete_user(db_info, '18012345678')
